#include "Sprite.h"

CSprite::CSprite(void)
{
}

CSprite::~CSprite(void)
{
}

CSprite::CSprite(int width, int height, float x, float y, int curFrame, int frameWidth, int frameHeight, float timeAnimation)
{
	this->m_texture = NULL;
	this->m_curFrame = curFrame;
	this->m_frameHeight = frameHeight;
	this->m_frameWidth = frameWidth;
	this->m_numCol = width/frameWidth;
	this->m_numRow = height/frameHeight;
	this->m_timeAnimation = timeAnimation;
	this->m_width = width;
	this->m_height = height;

	// Init rect
	int a = this->m_curFrame % this->m_numCol;
	int b = this->m_curFrame / this->m_numCol;
	this->m_rect.left = a * this->m_frameWidth;
	this->m_rect.right = this->m_rect.left + this->m_frameWidth;
	this->m_rect.top = (long)b * this->m_frameHeight;
	this->m_rect.bottom = this->m_rect.top + this->m_frameHeight;

	// Init pos
	this->m_pos = D3DXVECTOR2(x, y);
	m_timeCurrent = 0;
}

void CSprite::UpdateRect()
{
	int x = this->m_curFrame % this->m_numCol;
	int y = this->m_curFrame / this->m_numCol;

	this->m_rect.left = x * this->m_frameWidth;
	this->m_rect.right = this->m_rect.left + this->m_frameWidth;
	this->m_rect.top = y * this->m_frameHeight;
	this->m_rect.bottom = this->m_rect.top + this->m_frameHeight;

}

void CSprite::Update(float gameTime)
{
	if (this->m_timeAnimation != 0)
	{
		Update(gameTime, 0, m_numCol * m_numRow - 1);
	}
	UpdateRect();
}

void CSprite::Update(float gameTime, int frameStart, int frameEnd)
{
	if (this->m_timeAnimation != 0)
	{
		if (this->m_timeCurrent > this->m_timeAnimation)
		{
			this->m_curFrame++;
			if (m_curFrame < frameStart)
				m_curFrame = frameStart;
			if (this->m_curFrame > frameEnd )//this->m_numCol * this->m_numRow
				this->m_curFrame = frameStart;

			UpdateRect();
			this->m_timeCurrent = 0;
		}
		else
			m_timeCurrent += gameTime;

	}
}

void CSprite::Init(LPDIRECT3DTEXTURE9 texture)
{
	this->m_texture = texture;
}

void CSprite::Draw(LPD3DXSPRITE spriteHandler)
{
	spriteHandler->Draw(this->m_texture, &this->m_rect, NULL, &D3DXVECTOR3(this->m_pos.x, this->m_pos.y, 0), D3DCOLOR_ARGB(255, 255, 255, 255));
}